package com.nearby.demand.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMMessage;
import com.easemob.chat.OnMessageNotifyListener;
import com.easemob.chat.OnNotificationClickListener;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.nearby.demand.ui.MainActivity;
import com.nearby.demand.utils.KLog;
import com.request.ok.http.OkHttpUtils;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by IME on 2015/12/27.
 */
public class AppMain extends Application {
    private String CER_XXX = "";
    private Context _context;
    public static  AppMain application;
    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        _context = getApplicationContext();
        initOkHttp();
        initSdkChat();
    }
    public void initOkHttp() {
        try {
            Fresco.initialize(getApplicationContext(), ImagePipelineConfigFactory
                    .getImagePipelineConfig(getApplicationContext()));
//            OkHttpUtils.getInstance().setCertificates(new InputStream[]{
//                    new Buffer()
//                            .writeUtf8(CER_XXX)
//                            .inputStream(),
//                    getAssets().open("mic_server.cer")});
            OkHttpUtils.getInstance().getOkHttpClient().setConnectTimeout(100000, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            KLog.e(e.toString());
        }
    }

    public void initSdkChat() {
        //初始化监听
        initEMChat();
        //初始化配置参数
        EMChat.getInstance().init(_context);
        EMChat.getInstance().setDebugMode(true);
        EMChat.getInstance().setAutoLogin(true);
        EMChatManager.getInstance().getChatOptions().setUseRoster(true);
    }

    private void initEMChat() {
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        if (processAppName == null
                || !processAppName.equalsIgnoreCase("com.juns.wechat")) {
            return;
        }
        EMChatOptions options = EMChatManager.getInstance().getChatOptions();
        // 获取到EMChatOptions对象
        // 设置自定义的文字提示
        options.setNotifyText(new OnMessageNotifyListener() {

            @Override
            public String onNewMessageNotify(EMMessage message) {
                return "你的好友发来了一条消息哦";
            }

            @Override
            public String onLatestMessageNotify(EMMessage message,
                                                int fromUsersNum, int messageNum) {
                return fromUsersNum + "个好友，发来了" + messageNum + "条消息";
            }

            @Override
            public String onSetNotificationTitle(EMMessage arg0) {
                return null;
            }

            @Override
            public int onSetSmallIcon(EMMessage arg0) {
                return 0;
            }
        });
        options.setOnNotificationClickListener(new OnNotificationClickListener() {

            @Override
            public Intent onNotificationClick(EMMessage message) {
                Intent intent = new Intent(_context, MainActivity.class);
                EMMessage.ChatType chatType = message.getChatType();
                if (chatType == EMMessage.ChatType.Chat) { // 单聊信息
                    intent.putExtra("userId", message.getFrom());
//                    intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE);
                } else { // 群聊信息
                    // message.getTo()为群聊id
                    intent.putExtra("groupId", message.getTo());
//                    intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
                }
                return intent;
            }
        });
        // IntentFilter callFilter = new
        // IntentFilter(EMChatManager.getInstance()
        // .getIncomingCallBroadcastAction());
        // registerReceiver(new CallReceiver(), callFilter);
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this
                .getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i
                    .next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm
                            .getApplicationInfo(info.processName,
                                    PackageManager.GET_META_DATA));
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }

}
